/**
 * 给你一个由'1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。

 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

 此外，你可以假设该网格的四条边均被水包围。
 输入：grid = [
 ["1","1","1","1","0"],
 ["1","1","0","1","0"],
 ["1","1","0","0","0"],
 ["0","0","0","0","0"]
 ]
 输出：1

 来源：力扣（LeetCode）
 链接：https://leetcode-cn.com/problems/number-of-islands
 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */

//TODO:岛屿的数量
function helper(grid, i, j, rows, cols) {
    if (i < 0 || j < 0 || i > rows - 1 || j > cols - 1 || grid[i][j] === '0') {
        return;
    }
    // 判断过了的话， 直接改为'0', 以后就不会被访问了
    grid[i][j] = '0'
    helper(grid, i - 1, j, rows, cols)
    helper(grid, i + 1, j, rows, cols)
    helper(grid, i, j - 1, rows, cols)
    helper(grid, i, j + 1, rows, cols)
}


function islandNum(grid) {
    let res = 0, rows = grid.length, cols = grid[0].length
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (grid[i][j] === '1') { // 如果是'1'才进行判断, 0 直接跳过
                helper(grid, i, j, rows, cols)// 这里就已经判断了当前是不是一个岛， 如果是已经return了， 就不会加一了， 否则加一
                res++
            }
        }
    }
    return res;
}

const grid = [
    ["1", "1", "1", "1", "0"],
    ["1", "1", "0", "1", "0"],
    ["1", "1", "0", "0", "0"],
    ["0", "0", "0", "0", "0"]
]

const grid1 = [
    ["1", "1", "0", "0", "0"],
    ["1", "1", "0", "0", "0"],
    ["0", "0", "1", "0", "0"],
    ["0", "0", "0", "1", "1"]
]


console.log(islandNum(grid));
console.log(islandNum(grid1));




function helperV2(grid, cols, rows, i, j){
    // 判断， 如果i
    if(i<0 || j < 0|| i > rows-1|| j >cols-1|| grid[i][j]==='0'){
        return;
    }
    helperV2(grid, cols, rows, i-1, j)
    helperV2(grid, cols, rows, i+1, j)
    helperV2(grid, cols, rows, i, j-1)
    helperV2(grid, cols, rows, i, j+1)
}

